import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.filter.*;

public class resize_canvas_ implements PlugInFilter 
{
	ImagePlus imp;
	ImageProcessor ip2;
	boolean fillBorder=true;
	int s0x,s0y,sx,sy,x0,y0;

	public int setup(String arg, ImagePlus imp) 
	{
		this.imp = imp;
		return DOES_8G+ DOES_16+ DOES_32+NO_CHANGES;
	}

	public void run(ImageProcessor ip) 
	{
		int i,j;
		s0x=ip.getWidth();
		s0y=ip.getHeight();
		GenericDialog dia = new GenericDialog("resize canvas", IJ.getInstance());
		dia.addNumericField("width of new image",s0x, 1);
		dia.addNumericField("height of new image",s0y, 1);
		dia.addNumericField("x0",x0,1);
		dia.addNumericField("y0",y0,1);
		
	
		
		dia.showDialog();
		
		if(dia.wasCanceled())
			return;
		if(dia.invalidNumber()) 
		{
			IJ.showMessage("Error", "Invalid input Number");
			return;
		}		
		
		sx =(int) (dia.getNextNumber());
		sy =(int) (dia.getNextNumber());
		x0 =(int) (dia.getNextNumber());
		y0 =(int) (dia.getNextNumber());
		
	
		
		if (!(
			(sx>0)&&
			(sy>0)&&
			(x0<sx)&&
			(y0<sy)&&
			((s0x+x0)<sx)&&
			((s0y+y0)<sy)
			))
		{
			IJ.write("Original image does not fit in new image...");
			return;
		}
	
		int typ=imp.getType();
		
		ip2=new ByteProcessor(1,1);
		
		if (typ==ImagePlus.GRAY8)
			ip2=new ByteProcessor(sx,sy);
		if (typ==ImagePlus.GRAY16)
			ip2=new ShortProcessor(sx,sy);
		if (typ==ImagePlus.GRAY32)
			ip2=new FloatProcessor(sx,sy);
				/*
					 - - -
					|a|b|c|
					 - - -
					|d|e|f|
					 - - -
					|g|h|i|
					 - - - 
					
				*/
				
		for(j=0;j<sy;j++)
			for(i=0;i<sx;i++)
			{
				if((i>=x0)&&(i<x0+s0x)&&(j>=y0)&&(j<y0+s0y))
					ip2.putPixelValue(i,j,ip.getPixelValue(i-x0,j-y0));
					/*e*/
					
				else
				{
					ip2.putPixelValue(i,j,0.0);
					
					
					
				}
			}	
			
		ImagePlus imp2=new ImagePlus(imp.getTitle()+"_extended",ip2);
		imp2.show();
		imp2.updateAndDraw();
		
		
	}

}
